const qiniu = require('qiniu');

const ACCESS_KEY = 'jYqiP-e4PWkU_wrdWdgIR9zP0cadPhhrLsJb_HFC';
const SECRET_KEY = 'u69_Je7_rwLwmOo42wWDxJYsTx0EMUmzpsQLtewL';

const mac = new qiniu.auth.digest.Mac(ACCESS_KEY, SECRET_KEY);

const options = {
  scope: 'xfxj', // 存储空间的名字
};

const putPolicy = new qiniu.rs.PutPolicy(options);
const uploadToken = putPolicy.uploadToken(mac);

const config = new qiniu.conf.Config();

config.regionsProvider = qiniu.httpc.Region.fromRegionId('z0');
const formUploader = new qiniu.form_up.FormUploader(config);
const putExtra = new qiniu.form_up.PutExtra();

export const qn_upload = async (key: string, file: NodeJS.ReadableStream) => {
  try {
    const { data, resp } = await formUploader.putStream(
      uploadToken,
      key,
      file,
      putExtra,
    );
    if (resp.statusCode === 200) {
      return data;
    } else {
      throw new Error('上传失败' + resp.statusCode);
    }
  } catch (error) {
    throw new Error(error);
  }
};
